//导入数据库实例 便于操作数据库
const db = require('../config/db')

//创建群
exports.acreateGroup = (data, res) => {
    let dat = {}
    if (data.imgurl == '') {
        dat = {
            userid: data.uid,
            groupname: data.groupname,
            time: new Date(),
        }
    } else {
        dat = {
            userid: data.uid,
            groupname: data.groupname,
            imgurl: data.imgurl,
            time: new Date(),
        }
    }
    //先检测群名是否有重复
    let s = 'select * from `group` where groupname = ?'
    db.query(s, [dat.groupname], (err, r) => {
        if (err) return r.sendMsg(err, 500)
        if (r.length != 0) return r.sendMsg('该群名已经存在,请换另一个', 400)
        else {
            let sql = 'insert into `group` set ?'
            //插入群表中
            db.query(sql, dat, (err, result) => {
                if (err) return res.sendMsg(err, 500)
                if (result.affectedRows != 1) return res.sendMsg('创建群失败', 400)
                else {  //建群成功
                    console.log(result);
                    // res.sendMsg('success',200,result)
                    //得到群id
                    let groupid = result.insertId
                    //添加新成员到群内
                    //添加群主入群
                    let udata = {
                        groupid: groupid,
                        userid: data.uid,
                        time: new Date(),
                        lastTime: new Date()
                    }
                    this.insertGroupUser(udata, res)
                    //添加好友入群
                    for (let i = 0; i < data.user.length; i++) {
                        let obj = {
                            groupid: groupid,
                            userid: data.user[i],
                            time: new Date(),
                            lastTime: new Date()
                        }
                        this.insertGroupUser(obj, res)
                    }
                    res.sendMsg('success', 200)
                }
            })
        }
    })
}

//创建群
exports.createGroup = (data, res) => {
    return new Promise(function (resolve, reject) {
        let dat = {}
        if (data.imgurl == '') {
            dat = {
                userid: data.user[data.user.length - 1],
                groupname: data.groupname,
                time: new Date(),
            }
        } else {
            dat = {
                userid: data.user[data.user.length - 1],
                groupname: data.groupname,
                imgurl: data.imgurl,
                time: new Date(),
            }
        }
        //先检测群名是否有重复
        let s = 'select * from `group` where groupname = ?'
        db.query(s, [dat.groupname], (err, r) => {
            if (err) return reject(err)
            if (r.length != 0) return res.sendMsg('该群名已经存在,请换另一个', 400)
            else {
                let sql = 'insert into `group` set ?'
                //插入群表中
                db.query(sql, dat, (err, result) => {
                    if (err) return reject(err)
                    if (result.affectedRows != 1) return res.sendMsg('创建群失败', 400)
                    else {  //建群成功
                        resolve(result)
                    }
                })
            }
        })
    }).then(result => {
        console.log(result);
        //得到群id
        let groupid = result.insertId
        //添加群主好友入群
        for (let i = 0; i < data.user.length; i++) {
            let obj = {
                groupid: groupid,
                userid: data.user[i],
                time: new Date(),
                lastTime: new Date()
            }
            this.insertGroupUser(obj)
        }
        let obj = {
            groupid: groupid,
            userid: data.user[data.user.length - 1],
            message: '群主创建群啦',
            types: 0,
            time: new Date()
        }
        //群主默认说一句话
        let sql = 'insert into `groupmsg` set ?'
        db.query(sql, obj, (err, result) => {
            if (err) console.log('创建群默认话失败');
            else console.log('创建群默认话成功');
        })
        res.sendMsg('success', 200)
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//添加群成员
exports.insertGroupUser = (data, res) => {
    let sql = 'insert into `groupuser` set ?'
    //一个个添加进群成员表中
    db.query(sql, data, (err, result) => {
        if (err) if (res) {
            return res.sendMsg(err, 500)
        } else console.log(err);
        if (result.affectedRows != 1) {
            if (res) {
                return res.sendMsg('添加失败', 400)
            } else console.log('添加失败');
        }
        else {
            console.log('添加成功!');
            if (res) res.sendMsg('success', 200)
        }
    })
}
//删除群成员
exports.deleteGroupUser = (data, res) => {
    let sql = 'delete from `groupuser` where userid = ?'
    db.query(sql, [data.uid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.affectedRows != 1) return res.sendMsg('删除失败', 400)
        else {
            res.sendMsg('success', 200)
        }
    })
}

//解散某群
exports.outGroup = (data, res) => {
    let sql = 'DELETE FROM `group` WHERE groupid = ?'  //删除群表的
    db.query(sql, [data.gid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.affectedRows != 1) return res.sendMsg('群删除失败', 400)
        else {
            let sql1 = 'DELETE FROM `groupuser` WHERE groupid = ?'
            db.query(sql1, [parseInt(data.gid)], (err, result1) => {
                if (err) return res.sendMsg(err, 500)
                if (result1.affectedRows == 0) return res.sendMsg('群成员删除失败', 400)
                else {
                    let sql2 = 'DELETE from `groupmsg` WHERE groupid = ?'
                    db.query(sql2, [parseInt(data.gid)], (err, result2) => {
                        if (err) return res.sendMsg(err, 500)
                        if (result2.affectedRows == 0 ) return res.sendMsg('群消息删除失败', 400)
                        else {
                            res.sendMsg('success', 200)
                        }
                    })
                }
            })
        }
    })
}



//获取某个群的群名，群创建者，群公告，群头像,群创建时间等等
exports.getGroupDetail = (data, res) => {
    let sql = 'SELECT a.groupid,b.createid,b.groupname,a.usernameInGroup,b.imgurl,b.notice,a.shield,b.time from' +
        ' (SELECT groupid,userid,usernameInGroup,shield FROM groupuser WHERE groupid = ? and userid = ?) as a,'
        + '(SELECT userid as createid,groupid,groupname,imgurl,time,notice FROM `group` WHERE groupid = ?) as b  ' +
        'WHERE  a.groupid = b.groupid '
    db.query(sql, [data.gid, data.uid, data.gid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.length == 0) return res.sendMsg('未找到群', 400)
        else {
            return res.sendMsg('success', 200, result)
        }
    })
}

//获取群成员信息
exports.getGroupMember = (gid, res) => {
    let sql = 'SELECT a.userid ,b.username,a.usernameInGroup,b.imgurl FROM `groupuser` as a,' +
        '(SELECT userid,username,imgurl FROM `user`) as b WHERE a.groupid = ? and a.userid = b.userid'
    db.query(sql, [gid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.length == 0) return res.sendMsg('未找到', 400)
        else {
            res.sendMsg('success', 200, result)
        }
    })
}


//修改群信息  群名，群头像，群公告
exports.updateGroup = (data, res) => {
    let sql
    if (data.type == 'imgurl') {
        sql = "update `group` set imgurl = ? where groupid = ?"
    } else if (data.type == 'groupname') {
        sql = "update `group` set groupname = ? where groupid = ?"
    } else if (data.type == 'notice') {
        sql = "update `group` set notice = ? where groupid = ?"
    }
    db.query(sql, [data.data, parseInt(data.groupid)], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        else return res.sendMsg('success', 200)
    })
}

//修改某个用户在某群的群内名 
exports.updateUserMarkNameInGroup = (data, res) => {
    let sql = 'UPDATE groupuser set usernameInGroup = ? WHERE userid = ? and groupid = ?'
    db.query(sql, [data.name, data.uid, data.gid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.affectedRows != 1) return res.sendMsg('修改失败', 400)
        else {
            res.sendMsg('success', 200)
        }
    })
}

